import React from "react";

class Hello extends React.Component {
  state = {
    count: 1,
    name: "张三",
  };

  /**
   * PS:
   *    1. 必须结合 componentDidUpdate 使用，否则无意义会报错
   *    2. 必须有返回值，或者一个 null, 返回值会作为 componentDidUpdate 的第三个参数
   *    3. 两个参数
   *        prevProps   更新之前的Props
   *        prevState   更新之前的State
   *    4. 应用场景
   *      1. 在更新真实DOM前的最后一刻获取DOM,实现滚动条记录保留之类的。
   */
  getSnapshotBeforeUpdate(prevProps, prevState) {
    console.log("=== getSnapshotBeforeUpdate prevState", prevState);
    console.log("=== getSnapshotBeforeUpdate this.state", this.state);
    console.log(document.querySelector("h2")?.innerHTML);
    return "我的天";
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log("=== componentDidUpdate snapshot", snapshot);
    console.log(document.querySelector("h2")?.innerHTML);
  }

  handleClickTwo = () => {
    this.setState((state) => ({
      count: state.count === 3 ? 3 : state.count + 1,
    }));
  };

  handleClickThree = () => {
    this.setState((state) => ({
      name: state.name === "张三~~~" ? "张三~~~" : state.name + "~",
    }));
  };

  render() {
    console.log("=== Hello Render");
    return (
      <div>
        <h2>
          Hello, {this.state.count}, {this.state.name}
        </h2>
        <button onClick={this.handleClickTwo}>普通更新Count</button>
        <button onClick={this.handleClickThree}>普通更新Name</button>
      </div>
    );
  }
}

class App extends React.Component {
  render() {
    return (
      <div>
        <h1>App</h1>
        <Hello />
      </div>
    );
  }
}

export default App;
